package com.hongqianping.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hongqianping.entity.GoodsTable;
import com.hongqianping.entity.GoodsType;
import com.hongqianping.service.GoodsTableService;
import com.hongqianping.service.GoodsTypeService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
public class IndexController {

    @Autowired
    private GoodsTableService goodsTableService;

    @Autowired
    private GoodsTypeService goodsTypeService;

    @GetMapping({"/", "/index", "/index.html"})
    public String index(Model model) {
        // 获取推荐商品
        List<GoodsTable> recommendedGoods = goodsTableService.lambdaQuery()
                                                 .eq(GoodsTable::getIsRecommend, true)
                                                 .last("limit 6") // 限制显示6个推荐商品
                                                 .list();
        model.addAttribute("recommendedGoods", recommendedGoods);
        model.addAttribute("pageTitle", "推荐商品"); // 添加页面标题

        // 获取导航栏所有商品类型
        List<GoodsType> goodsTypes = goodsTypeService.list();
        model.addAttribute("goodsTypes", goodsTypes);

        return "index"; // 解析到 src/main/resources/templates/user/index.html
    }

    @GetMapping("/category")
    public String getGoodsByCategory(@RequestParam("typeId") Integer typeId, Model model) {
        List<GoodsTable> goodsList;
        String categoryName = "所有商品";

        // 获取导航栏所有商品类型
        List<GoodsType> goodsTypes = goodsTypeService.list();
        model.addAttribute("goodsTypes", goodsTypes);

        if (typeId != null) {
            LambdaQueryWrapper<GoodsTable> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(GoodsTable::getGoodstypeId, typeId);
            goodsList = goodsTableService.list(queryWrapper);

            GoodsType selectedType = goodsTypeService.getById(typeId);
            if (selectedType != null) {
                categoryName = selectedType.getTypename();
            }
        } else {
            // 如果未提供typeId，显示所有商品
            goodsList = goodsTableService.list();
        }

        model.addAttribute("recommendedGoods", goodsList); // 为简洁起见，复用recommendedGoods属性名
        model.addAttribute("pageTitle", categoryName + " 分类商品"); // 分类页面动态标题

        return "index"; // 复用 index.html 模板
    }

    @GetMapping("/goodsDetail")
    public String goodsDetail(@RequestParam("id") Integer id, Model model) {
        GoodsTable goods = goodsTableService.getById(id);
        if (goods != null) {
            model.addAttribute("goods", goods);
            // 根据goodstypeId获取商品类型
            if (goods.getGoodstypeId() != null) {
                GoodsType goodsType = goodsTypeService.getById(goods.getGoodstypeId());
                model.addAttribute("goodstype", goodsType);
            }
        } else {
            // 可选地处理未找到商品的情况，例如重定向到错误页面或首页
            model.addAttribute("error", "未找到该商品详情。");
        }

        // 获取导航栏所有商品类型
        List<GoodsType> goodsTypes = goodsTypeService.list();
        model.addAttribute("goodsTypes", goodsTypes);

        return "detail"; // 将视图名称从 "user/detail" 改为 "detail"
    }

    @GetMapping("/search")
    public String searchGoods(@RequestParam(value = "keyword", required = false) String keyword,
                            @RequestParam(value = "typeId", required = false) Integer typeId,
                            Model model) {
        List<GoodsTable> searchResults;
        LambdaQueryWrapper<GoodsTable> queryWrapper = new LambdaQueryWrapper<>();

        // 如果有关键词，按商品名称搜索
        if (keyword != null && !keyword.trim().isEmpty()) {
            queryWrapper.like(GoodsTable::getGname, keyword.trim());
        }

        // 如果选择了分类，按分类筛选
        if (typeId != null) {
            queryWrapper.eq(GoodsTable::getGoodstypeId, typeId);
        }

        // 执行查询
        searchResults = goodsTableService.list(queryWrapper);
        if (searchResults == null) {
            searchResults = new java.util.ArrayList<>(); // 确保它永远不是null
        }

        // 获取所有商品分类（用于分类筛选）
        List<GoodsType> goodsTypes = goodsTypeService.list();
        if (goodsTypes == null) {
            goodsTypes = new java.util.ArrayList<>(); // 确保它永远不是null
        }
        
        // 获取当前选中的分类名称
        String selectedTypeName = "所有分类";
        if (typeId != null) {
            GoodsType selectedType = goodsTypeService.getById(typeId);
            if (selectedType != null) {
                selectedTypeName = selectedType.getTypename();
            }
        }

        model.addAttribute("searchResults", searchResults);
        model.addAttribute("keyword", keyword);
        model.addAttribute("goodsTypes", goodsTypes);
        model.addAttribute("selectedTypeId", typeId);
        model.addAttribute("selectedTypeName", selectedTypeName);
        model.addAttribute("pageTitle", "搜索结果 - " + selectedTypeName +
            (keyword != null && !keyword.trim().isEmpty() ? " - " + keyword : ""));

        return "search_results";
    }

} 